<template>
  <div>
    <TopFilter :list="topFilterList" :cols="3" :collapse="true" @filterChange="changeHandle"></TopFilter>
    <FilterTable
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'rows'"
      columnsRef="lxjshhftask"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="onRowSelectChange"
    ></FilterTable>
    <div :style="{ margin: '20px' }">
      <div :style="{ width: '380px', float: 'left' }">
        <FormPanel ref="formPanel" :list="formList" :cols="3" :labelWidth="110" :formType="type" :isSubmitBtn="false" />
      </div>
      <div :style="{ float: 'left' }">
        <AjaxButton type="primary" :click="openDistribution" :disabled="buttonDisabled">任务分派</AjaxButton>
        <el-button size="small" type="primary" @click="() => this.openHandler('repairHistory', {})" :disabled="disabledS">维修历史</el-button>
        <AjaxButton type="primary" :disabled="avgButtonDisabled" :click="openDistribution">平均分派</AjaxButton>
      </div>
    </div>
    <!-- 维修历史-->
    <BaseDialog :visible.sync="historyActions.visible" :title="historyActions.title" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <repairHistory :carInfo="carInfoObj" :vin="carVin" @close="close_history" />
    </BaseDialog>
  </div>
</template>

<script>
import moment from 'moment';
import { confirmAction } from '@/utils';
import { dictionary } from '@/utils/dictMixin';
import repairHistory from '@/pages/repair/repairReception/customer/repairHistory'; // 维修历史
import { getAfterVisitInfo, getAfterVisitInfoExcelList, getAllUser, taskAssignment } from '@/api/customerRepair/afterSaleVisit/resultEntry';
import { searchRoleByCode } from '@/api/common/empSelect/index';
import dictCode from '@/utils/dictCode';
import { searchRoleByCodes } from '@/api/customerCare/visitAllocation/getVisitInfo';
import { getWxlxSelect } from '@/api/repair/repairReception/customer';
import { exportExcelFile } from '@/utils/index';
import { isFormEmpty, notifyAction, findTableItem } from '@/utils';
import { getPinpSelect, getChexSelect, getCheModelSelect } from '@/api/repair/repairReception/customer/brand.js';
import { getRegion } from '@/api/customerRepair/customerInfo/ownerVehicleManagement';

export default {
  name: 'taskDistribution',
  components: {
    repairHistory
  },
  mixins: [dictionary],
  props: {
    type: {
      type: String
    }
  },
  data() {
    this.BaseTable = null;
    this.allData = null; // 选中后存入对象
    return {
      topFilterList: this.createTopFilterList(),
      columns: this.createTableColumns(),
      formList: this.createFormList(),
      actions: { title: '', type: '', visible: false },
      historyActions: { title: '', type: '', visible: false }, // 维修历史界面
      fetchApi: getAfterVisitInfo,
      fetchParams: { traceTag: 10041002 },
      repairHistoryData: {}, // 维修历史数据
      options: [],
      value: '',
      trace: null, // 跟踪员
      buttonDisabled: false, // 任务分派按钮是否只读
      avgButtonDisabled: true, // 平均分派按钮是否只读
      regionList: [], // 省市区列表
      userList: [], //人员列表
      carVin: '', // 维修历史需要底盘号参数
      disabledS: true,
      carInfoObj: {} // 维修历史需要的对象
    };
  },
  created() {
    this.getDcrcAdvisor();
    // 获取品牌
    this.getBrand();
    this.getAllUser();
    // 获取省市区
    this.queryRegion();
    this.getWxtypeSelect();
    // this.serviceConsultant();
  },
  mounted() {
    this.BaseTable = this.$refs.table;
  },
  methods: {
    createTopFilterList() {
      return [
        {
          type: 'RANGE_DATE',
          label: '结清日期',
          style: { minWidth: '220px' },
          fieldName: 'deltveryBeginDate|deltveryEndDate'
        },
        {
          type: 'RANGE_DATE',
          label: '开单日期',
          style: { minWidth: '220px' },
          fieldName: 'roCreateBeginDate|roCreateEndDate',
          valueFormat: 'yyyy-MM-dd'
        },
        {
          type: 'INPUT',
          label: '车牌号',
          fieldName: 'license'
        },
        // {
        //   type: 'SELECT',
        //   label: '回访时间',
        //   fieldName: 'traceTime',
        //   itemList: this.createDictList('8029')
        // },
        {
          type: 'SELECT',
          label: '品牌',
          fieldName: 'brand',
          itemList: [],
          change: val => {
            this.changePinpSelect(val);
          }
        },
        {
          type: 'SELECT',
          label: '车系',
          fieldName: 'series',
          itemList: [],
          change: val => {
            this.changeChexSelect(val);
          }
        },
        {
          type: 'SELECT',
          label: '车型',
          fieldName: 'model',
          itemList: []
        },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin'
        },
        {
          type: 'SELECT',
          label: '跟踪员',
          fieldName: 'stalker',
          itemList: []
        },
        {
          type: 'SELECT',
          label: '维修类型',
          fieldName: 'repairTypeCode',
          itemList: [],
          initialValue: ''
        },
        {
          type: 'SELECT',
          label: '是否分配',
          initialValue: 10041002,
          fieldName: 'traceTag',
          itemList: this.createDictList(1004)
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '品牌',
          dataIndex: 'brandName'
        },
        {
          title: '跟踪员',
          dataIndex: 'stalker',
          width: 150
        },
        {
          title: '是否分配',
          dataIndex: 'traceTag',
          width: 150,
          dictItems: this.createDictList(1004)
        },
        {
          title: '工单号',
          dataIndex: 'roNo',
          width: 150
        },
        {
          title: '车牌号',
          dataIndex: 'license',
          width: 150
        },
        {
          title: 'VIN',
          dataIndex: 'vin',
          width: 150
        },
        {
          title: '结清日期',
          dataIndex: 'deliveryDate',
          width: 150,
          dateFormat: 'yyyy-MM-dd'
        },
        {
          title: '销售日期',
          dataIndex: 'salesDate',
          width: 150,
          dateFormat: 'yyyy-MM-dd'
        },
        {
          title: '车系',
          dataIndex: 'seriesName'
        },
        {
          title: '车型',
          dataIndex: 'modelName'
        },
        {
          title: '颜色',
          dataIndex: 'color',
          width: 150
        },
        {
          title: '服务专员',
          dataIndex: 'serviceAdvisor',
          width: 150,
          dictItems: []
        },
        {
          title: '进厂里程',
          dataIndex: 'inMileage',
          width: 150
        },
        {
          title: '出厂里程',
          dataIndex: 'outMileage',
          width: 150
        },
        {
          title: '车主编号',
          dataIndex: 'ownerNo',
          width: 150
        },
        {
          title: '车主',
          dataIndex: 'ownerName',
          width: 150
        },
        {
          title: 'E-MAIL',
          dataIndex: 'email',
          width: 150
        },
        {
          title: '车主地址',
          dataIndex: 'address',
          width: 150
        },
        {
          title: '城市',
          dataIndex: 'city',
          width: 150,
          dictItems: []
        },
        {
          title: '邮编',
          dataIndex: 'zipCode',
          width: 150
        },
        {
          title: '送修人',
          dataIndex: 'deliverer',
          width: 150
        },
        {
          title: '送修人性别',
          dataIndex: 'delivererGender',
          width: 150,
          render: props => {
            return <span>{this.createDictText(props.row.delivererGender, '8012')}</span>;
          }
        },
        // {
        //   title: '送修人电话',
        //   dataIndex: 'delivererPhone',
        //   width: 150
        // },
        {
          title: '送修人手机',
          dataIndex: 'delivererMobile',
          width: 150
        },
        {
          title: '维修类型名称',
          dataIndex: 'repairTypeCode',
          width: 150
        },
        {
          title: '开单日期',
          dataIndex: 'roCreateDate',
          width: 150,
          dateFormat: 'yyyy-MM-dd'
        },
        {
          title: '结算单号',
          dataIndex: 'balanceNo',
          width: 150
        },
        // {
        //   title: '关单人',
        //   dataIndex: 'obligatedOperator',
        //   width: 150
        // },
        {
          title: '客户备注',
          dataIndex: 'remark',
          width: 150
        },
        {
          title: '维修技师',
          dataIndex: 'TECHNICIAN_LIST',
          width: 150
        }
        // {
        //   title: '车主备注',
        //   dataIndex: 'ownerRemark',
        //   width: 150
        // },
        // {
        //   title: '车辆备注',
        //   dataIndex: 'vehicleRemark',
        //   width: 150
        // }
      ];
    },
    createFormList() {
      return [
        {
          type: 'MULTIPLE_SELECT',
          label: '跟踪员',
          fieldName: 'tracerList',
          style: { width: '250px' },
          itemList: [],
          rules: [{ required: true, message: '请选择跟踪员', trigger: 'blur' }],
          change: val => {
            if (val.length > 1) {
              this.buttonDisabled = true;
              this.avgButtonDisabled = false;
            } else {
              this.buttonDisabled = false;
              this.avgButtonDisabled = true;
            }
          }
        }
      ];
    },
    // 选中事件
    onRowSelectChange(val) {
      if (!val.length) {
        this.disabledS = true;
        this.allData = null;
      } else {
        this.disabledS = false;
        this.allData = val;
      }
    },
    changeHandle(val) {
      this.fetchParams = Object.assign({}, val, { xhrAbort: false });
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    // 清空下拉框表当控件的值和下拉列表
    clearFormItem(item) {
      item.initialValue = undefined;
      item.itemList = [];
    },
    // 所有用户
    async getAllUser() {
      const res = await getAllUser();
      console.log('所有用户', res);
      let userListDict = res.data.map(x => ({ value: x.userId, text: x.employeeName }));
      this.userList = userListDict;
      let targetTableItems = [findTableItem(this.columns, 'serviceAdvisor'), findTableItem(this.columns, 'stalker')];
      targetTableItems.forEach(item => {
        item.dictItems = userListDict;
      });
    },
    // dcrc客服专员 跟踪员
    async getDcrcAdvisor() {
      let roleParm = {
        role: dictCode.CUSTOMER_SERVICE_SPECIALIST
      };
      const res = await searchRoleByCodes(roleParm);
      this.topFilterList.find(item => item.fieldName === 'stalker').itemList = this.formList.find(item => item.fieldName === 'tracerList').itemList = res.data.map(x => ({
        value: x.userId,
        text: x.employeeName
      }));
    },
    // 获取维修项目类型
    async getWxtypeSelect() {
      const res = await getWxlxSelect();
      if (res.resultCode === 200) {
        if (res.errMsg) {
          notifyAction(res.errMsg, 'error');
        } else {
          let repairTypeDict = (this.topFilterList.find(x => x.fieldName === 'repairTypeCode').itemList = res.data.map(x => ({
            value: x.REPAIR_TYPE_CODE,
            text: x.REPAIR_TYPE_NAME
          })));
          let targetTableItems = [findTableItem(this.columns, 'repairTypeCode')];
          targetTableItems.forEach(item => {
            item.dictItems = repairTypeDict;
          });
        }
      }
    },
    // 品牌
    async getBrand() {
      const res = await getPinpSelect();
      if (res.resultCode === 200) {
        if (res.errMsg) {
          notifyAction(res.errMsg, 'error');
        } else {
          this.topFilterList.find(item => item.fieldName === 'brand').itemList = res.data.map(x => ({
            value: x.brandId + '',
            text: x.brandName
          }));
        }
      }
    },
    // 车系
    async getSeries(brandsid) {
      const res = await getChexSelect(brandsid);
      if (res.resultCode === 200) {
        if (res.errMsg) {
          notifyAction(res.errMsg, 'error');
        } else {
          this.topFilterList.find(item => item.fieldName === 'series').itemList = res.data.map(x => ({
            value: x.seriesId + '',
            text: x.seriesName
          }));
        }
      }
    },
    // 车型
    async getModel(brandsid, seriessid) {
      const res = await getCheModelSelect(brandsid, seriessid);
      if (res.resultCode === 200) {
        if (res.errMsg) {
          notifyAction(res.errMsg, 'error');
        } else {
          this.topFilterList.find(item => item.fieldName === 'model').itemList = res.data.map(x => ({
            value: x.modelId + '',
            text: x.modelName
          }));
        }
      }
    },
    // 品牌下拉框改变时
    changePinpSelect(id) {
      this.clearFormItem(this.topFilterList.find(item => item.fieldName === 'series'));
      this.clearFormItem(this.topFilterList.find(item => item.fieldName === 'model'));
      if (!id) return;
      // 获取车系
      this.getSeries(id);
    },
    // 车系下拉框改变时
    changeChexSelect(id) {
      this.clearFormItem(this.topFilterList.find(item => item.fieldName === 'model'));
      if (!id) return;
      // 获取车型
      this.getModel(this.topFilterList.find(item => item.fieldName === 'brand').initialValue, id);
    },
    // 获取省市区列表
    async queryRegion() {
      const allRegion = await getRegion();
      let regionList = allRegion.data.map(x => ({ value: x.regionId, text: x.regionName }));
      let targetTableItems = [findTableItem(this.columns, 'city')];
      targetTableItems.forEach(item => {
        item.dictItems = regionList;
      });
    },
    // table省市区转换
    getText(type, val) {
      if (type === 'region') {
        return this.regionList.find(x => x.value === val) ? this.regionList.find(x => x.value === val).text : '';
      }
    },
    // 任务分派/平均分派
    async openDistribution() {
      const [err, data] = await this.$refs.formPanel.GET_FORM_DATA();
      if (err) return;
      const roIdList = [];
      if (!this.allData.length) {
        return notifyAction('请选择工单', 'warning');
      } else {
        if (data.tracerList.length === 1) {
          let username = this.userList.find(x => x.value === data.tracerList[0]) ? this.userList.find(x => x.value === data.tracerList[0]).text : '';
          await confirmAction('确认是否将回访分配给' + username, 'warning');
        }
        for (let i = 0; i < this.allData.length; i++) {
          roIdList.push(this.allData[i].roNo);
        }
      }
      const res = await taskAssignment({ ...data, roIdList: roIdList });
      if (res.resultCode === 200) {
        if (res.errMsg) {
          return notifyAction(res.errMsg, 'error');
        } else {
          notifyAction('分配成功！');
          // this.formList.find(item => item.fieldName === 'tracerList').initialValue = undifined;
          this.fetchParams = { ...this.fetchParams };
        }
      }
    },
    // 车主导出
    afterSaleExportData() {
      getAfterVisitInfoExcelList(this.fetchParams).then(res => {
        // console.log(res);
        exportExcelFile(res, '回访分配信息导出');
      });
    },
    openHandler(type, val) {
      if (isFormEmpty(this.allData) || this.allData.length > 1) {
        return notifyAction('请选择一条数据！', 'warning');
      } else {
        console.log('维修历史');
        console.log(this.allData);
        if (type === 'repairHistory') {
          if (isFormEmpty(this.allData[0].vin)) {
            return notifyAction('车辆VIN不能为空！', 'warning');
          }
          this.historyActions = { title: '维修历史', type: 'detail', visible: true };
          this.carVin = this.allData[0].vin;
          this.carInfoObj = this.allData[0];
        }
      }
    },
    // 关闭维修历史界面
    close_history(val) {
      this.historyActions.visible = val;
    }
  }
};
</script>

<style lang="less" scoped></style>
